<template>
  <div>
    <div class="box" ref="box">
      <div v-if="isBtn">
        <van-button type="primary" size="small" icon="search" :disabled="disabledSearch" @click="onclick">{{ btnShowText }}</van-button>
      </div>
      <div class="" v-else>
        <van-field 
          v-model="input"
          :label="label"
          label-width="130"
          :size="size"
          clearable
          :style="style"
          :disabled="disabled"
          :placeholder="placeholder"
          :fetch-suggestions="querySearchAsync"
          :readonly="readonly"
          right-icon="search"
          @click-right-icon="onclick"
          ref="inputObj"
          @blur.stop.native="onblur"
          @clear="onTableRowClick({});errMs = '';">
          <!-- <template #append>
            <el-button :disabled="disabledSearch" @click="onclick" icon="Search"/>
          </template> -->
          <template #default="{ item }">
            <div @mouseenter="onmouseenter" @mouseleave="onmouseleave">
              <slot name="selectItem" :item="item"></slot>
            </div>
          </template>
        </van-field>
      </div>
    </div>
    <van-popup 
      v-model:show="open" 
      z-index="100000000000000" 
      :style="{ width: '100%',maxHeight: '100vh',  }">
      <div class="kpi-list-content">
        <!-- <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            error-text="请求失败，点击重新加载"
            @load="getList"
            :offset='0'
          >
           
          </van-list>
        </van-pull-refresh> -->
        <div class="list">
          <van-empty image="search" description="暂无数据" v-if="tableDialogData.length === 0" />
          <ul v-else>
            <li v-for="(item,index) in tableDialogData" :key="item.id" @click="onTableRowClick(item, index)" :class="{'active': oIndex === index}">
              <slot name="queryTable" :item="item" ></slot>
              <van-icon name="success" class="active-ico" v-if="oIndex === index" />
            </li>
          </ul>
        </div>
        <div class="btns">
          <!-- <van-button icon="certificate" type="primary" class="btns-a" round  @click="handleOk" color="#4fa2f7" :disabled=" !(typeof(oIndex) === 'number') ">确认选择</van-button> -->
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import {doGet} from '@/config/http'
import InputTag from "@/components/InputTag/index.vue";
import {svc, isNullOrUndefinedOrEmpty, getListPageSize} from "@/config/common";
import MultiplePageSelectionTable from "@/components/MultiplePageSelectionTable/index.vue";
import { ref, computed, watch } from 'vue'

  const emit = defineEmits(['update:value', 'onchange', 'changeErrMs', 'callback', ]);

  const props = defineProps({
    rowKey: {
      type: String,
      default: 'id'
    },
    rowClassName: {
      type: Function,
      default: function () {
        return ''
      }
    },
    placeholder: {
      type: String,
      default: ''
    },
    modelValue: String,
    keyName: {
      type: String,
      required: true,
    },
    label: {
      type: String,
      required: true,
    },
    keyShow: {
      type: String,
      required: true,
    },
    isNotShow: {
      type: Boolean,
      default: false
    },
    size: {
      default: 'default'
    },
    svc: {
      type: String,
      default: svc
    },
    urlPage: {type: String, required: true},
    urlIds: {type: String, required: true},
    style: {
      default: ''
    },
    title: {
      type: String
    },
    isDataList: {
      type: Boolean,
      default: false
    },
    params: {
      type: Object,
      default() {
        return {}
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    searchEnabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    },
    //是否添加重新渲染描述
    isAddDes: {
      type: Boolean,
      default: false
    },
    //列表清空，输入错误值清空
    clearValue: {
      type: Boolean,
      default: false
    },
    isMultiple: {
      type: Boolean,
      default: false
    },
    maxHeight: {
      type: String,
      default: '600'
    },
    isExist: {
      type: Function,
      default: (row, item, rowKey = 'id') => {
        return row[rowKey] === item[rowKey]
      }
    },
    isBtn: {
      type: Boolean,
      default: false
    },
    btnShowText: {
      type: String,
      default: '选择'
    }
  })
  let row = ref(null)
  let input  = ref('')
  let open = ref(false)
  // let loading = ref(false)
  let listQuery = ref({
    pageNum: 1,
    pageSize: getListPageSize(),
  })

  let changeData = ref({
    pageNum: 0,
    pageSize: 10,
  })

  let tableDialogData = ref([])

  let total = ref(0)
  let tStop = ref(null)
  let list = ref([])
  let errMs = ref('')
  let inputObj = ref(null)
  let isNotEnter = ref(false)
  let isNotInit = ref(false)
  let isSearchAsync = ref(false)
  let activeName = ref('query')
  let selectionList = ref([])


  let tableRadio = ref('')
// let list = ref([])
  let loading = ref(false)
  let finished = ref(false)
  let refreshing = ref(false)
  let isShowModel = ref(false)
  let expenditureKpiObj = ref(null)
  let oIndex = ref(null)

  const disabledSearch = computed(() => {
    const {searchEnabled, disabled} = this
    if (searchEnabled) {
      return false
    }
    return disabled
  })

  watch(() => [props.params, props.modelValue, props.clearValue], (vals, olds) => {
    // console.log('val-----------',val)
    if (vals[0]) {
      Object.assign(listQuery.value, vals[0])
    }
    if(vals[1]) {
      if (!isNullOrUndefinedOrEmpty(vals[1]) && !isNullOrUndefinedOrEmpty(props.urlIds)) {
        doGet(svc, props.urlIds, {ids: vals[1]}, false).then(res => {
          input.value = res?.map(m => m[props.keyShow]).join(',')
        })
      }
      if (!open.value && vals[1] !== olds[1]) {
        init()
      }
      
    }
    if (vals[2]) {
      input.value = ''
    }
    }, {immediate: true, deep: true}
  );


  const init = () => {
    input.value = props.modelValue
    console.debug('input.value+++++', input.value)
    row.value = null
    if (isNotInit.value) {
      return false
    }
    if (props.params) {
      Object.assign(listQuery.value, props.params)
    }
  }
  const handleClose = () => {
    open.value = false
  }
  const onclick = () => {
    listQuery.value = {
      ...props.params,
      pageNum: 1,
      pageSize: getListPageSize(),
    }
    open.value = true

    getList()
  }
  const handleSelect = (row) => {
    inputObj.value.blur()
    row.value = row
    onTableRowClick(row.value)
    isSearchAsync.value = false
  }
  const onTableRowClick = (row, column, event, isAuto) => {
    if (row.disabled) {
      return false
    }
    row.value = row
    if (props.isNotShow) {
      input.value = ''
    } else {
      input.value = row.value && (props.keyShow && row.value[props.keyShow]) || row.value[props.keyName] || ''
      if (!input.value) {
        setTimeout(() => {
          inputObj.value.blur()
        })
    }
    }
    isNotInit.value = true
    emit('update:modelValue', row[props.keyName])
    emit('onchange', row, isAuto)
    setTimeout(() => {
      isNotInit.value = false
    })
    errMs.value = ''
    emit('changeErrMs', errMs.value, input.value)
    setTimeout(() => {
      open.value = false
    })
  }
  const handleSelectionChange = (data) => {
    selectionList.value = data
  }
  const handleOk = () => {
    if (props.isMultiple) {
      input.value = this.selectionList.map(item => {
        return item[row.valueKey]
      }).join(',')
      emit('update:modelValue', input.value)
      emit('onchange', selectionList.value)
    }
    open.value = false
  }
  const handleFilter = () => {
    listQuery.value.pageNum = 1
    this.getList()
    if (props.isMultiple) {
      this.$refs.mpTable?.initSelect()
    }
  }
  const handleResetQuery = () => {
    this.$refs.filterFrom.resetFields()
  }
  const getList = () => {
    //自定义方法嵌套组件冒泡，没啥好的解决办法，同时解决多组件同时请求
    tStop.value = setTimeout(() => {
      if (tStop.value) {
        clearTimeout(tStop.value)
      }
      loading.value = true
      doGet(svc, props.urlPage, listQuery.value, false).then(res => {
        if (res && res?.records && res.records?.length > 0 || (props.isDataList && res?.length > 0)) {
          if (props.isDataList) {
            tableDialogData.value = res
            total.value = 0
          } else {
            tableDialogData.value = res?.records
            total.value = parseInt(res['total']) || 0
          }
          if (props.isAddDes) {
            emit('callback', tableDialogData.value)
          }
        } else {
          tableDialogData.value = []
          total.value = 0
        }
        if (props.isMultiple) {
          this.$refs.mpTable?.setList(tableDialogData.value)
        }
        loading.value = false
      })
    })
  }
  const querySearchAsync = (queryString, cb) => {
    let list = []
    if (isNotEnter.value && queryString.length > 0) {
      errMs.value = ''
      let params = {
        ...props.params,
        pageNum: 1,
        pageSize: 100
      }
      params[props.keyName] = queryString
      doGet(svc, props.urlPage, params, false).then(res => {
        if (res && res?.records && res.records.length > 0 || (props.isDataList && res?.length > 0)) {
          if (props.isDataList) {
            list = res
          } else {
            list = res?.records
            total.value = parseInt(res['total'])
          }
          if (props.isAddDes) {
            emit('callback', list)
            setTimeout(() => {
              cb && cb(list)
            }, 500)
          } else {
            cb && cb(list)
          }
        } else {
          errMs.value = ' '
          cb && cb(list)
        }
      })
    } else {
      cb && cb(list)
    }
  }
  const onblur = () => {
    this.isChange = false
    this.tOpenTable = setTimeout(() => {
      input.value = row.value && (props.keyShow && row.value[props.keyShow] || row.value[props.keyName]) || ''
    }, 300)
  }
  const handleInputTag = () => {
    emit('update:modelValue', input.value)
  }
  const onmouseenter = () => {
    isSearchAsync.value = true
  }
  const onmouseleave = () => {
    isSearchAsync.value = false
  }

</script>

<style scoped lang="scss">
.kpi {
    width: 100%;
    height: 100vh;
    background-color: #f5f2f2;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    overflow-y: auto;
}

.kpi-list-content {
  width: 100%;
  height: 100%;
}
.list-text {
  width: 70%;
  overflow: hidden; /* 确保超出容器的内容被裁剪 */
  white-space: nowrap; /* 确保文本在一行内显示 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  // color: #1db0bf;
}
.list {
  width: 100%;
  height: calc( 100vh - 8rem);
  & ul {
    width: 100%;
    height: 100%;
    padding: 0 .625rem;
    scroll-behavior: smooth;
    overflow-y: auto;
    & li {
      border-bottom: 1px solid #C3C3C3;
      border-radius: 6px;
      margin: .625rem 0;
      background: #fff;
      padding: .625rem;
      box-shadow:0 0 5px var(--van-gray-5);
      position: relative;
      .list-left {
        display: flex;
        justify-content: space-between;
        // margin-top: .625rem;
       
      }
      .list-m {
        display: flex;
        align-items: center;
        // justify-content: space-between;
        flex-wrap: wrap;
        margin-top: .625rem;
        & span {
          color: 000;
          font-size: .875rem;
          border: 1px solid #000;
          padding: 0.1rem .5rem;
          display: inline-block;
          margin: 0 .3125rem;
          border-radius: 2px;
        }
      }
      .list-btn {
        display: flex;
        justify-content: flex-end;
        margin-top: .625rem;
      }
      & span {
        // color: #95d475;
        font-size: .875rem;
        font-weight: bold;
        // color: #000;
      }
    }
    & li.active {
      background: #fff1f1;
      box-shadow:0 0 5px #9b0f65;
    }
    .active-ico {
      position: absolute;
      left: 0;
      bottom: 0;
      background: #dfc059;
      color: #fff;
      border-radius: 50%;
    }
  }
}
.btns {
  width: 100%;
  // padding: 0 .625rem;
  overflow: hidden;
  position: fixed;
  bottom: 0.2rem;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.list-amount {
  padding: .3rem 0.8rem;
  border-radius: 30px;
  color: #fff;
  background: #dfc059;
  
}
.model-head {
  font-size: 1.5rem;
  font-weight: bold;
  margin-top: 2rem;
  text-align: center;
}
.model-content {
  padding: 0 1.2rem;
}
.content {
  padding: .625rem 0;
  color: var(--van-gray-10);
  display: flex;
  // align-items: center;
}
.content span:nth-child(1) {
  display: inline-block;
  text-align: top;
  // width: 46%;
  min-width: 25%;
}
</style>
